/**
 * Project Name:fire-industry-DM-center
 * File Name:DataSourceSecondaryConfig.java
 * Package Name:com.firestone.config.mybatis
 * Date:2018年3月13日下午3:21:13
 *
*/

package com.firestone.config.mybatis;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;

/**
 * @Description: TODO(第二数据源连接配置)
 * @author CAIYJ
 * @date 2018年3月13日 下午3:21:13
 */
@Configuration
@MapperScan(basePackages = "com.firestone.dao.secondary", sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class DataSourceSecondaryConfig {

    private static final Logger logger = LogManager
            .getLogger(DataSourceSecondaryConfig.class);

    @Bean(name = "secondaryDataSource", initMethod = "init", destroyMethod = "close")
    public DruidDataSource dataSource(
            DruidConfigSecondaryProperties druidConfigSecondaryProperties)
                    throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(
                druidConfigSecondaryProperties.getDriverClassName());
        druidDataSource.setUrl(druidConfigSecondaryProperties.getUrl());
        druidDataSource
                .setUsername(druidConfigSecondaryProperties.getUsername());
        druidDataSource
                .setPassword(druidConfigSecondaryProperties.getPassword());
        druidDataSource
                .setInitialSize(druidConfigSecondaryProperties.getMinIdle());
        druidDataSource.setMinIdle(druidConfigSecondaryProperties.getMinIdle());
        druidDataSource
                .setMaxActive(druidConfigSecondaryProperties.getMaxActive());
        druidDataSource.setMaxWait(druidConfigSecondaryProperties.getMaxWait());
        druidDataSource
                .setTimeBetweenEvictionRunsMillis(druidConfigSecondaryProperties
                        .getTimeBetweenEvictionRunsMillis());
        druidDataSource.setMinEvictableIdleTimeMillis(
                druidConfigSecondaryProperties.getMinEvictableIdleTimeMillis());
        druidDataSource.setValidationQuery(
                druidConfigSecondaryProperties.getValidationQuery());
        druidDataSource.setTestWhileIdle(
                druidConfigSecondaryProperties.getTestWhileIdle());
        druidDataSource.setTestOnBorrow(
                druidConfigSecondaryProperties.getTestOnBorrow());
        druidDataSource.setTestOnReturn(
                druidConfigSecondaryProperties.getTestOnReturn());
        druidDataSource.setPoolPreparedStatements(
                druidConfigSecondaryProperties.getPoolPreparedStatements());
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(
                druidConfigSecondaryProperties
                        .getMaxPoolPreparedStatementPerConnectionSize());
        druidDataSource.setFilters(druidConfigSecondaryProperties.getFilters());
        return druidDataSource;
    }

    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(
            @Qualifier("secondaryDataSource") DataSource dataSource,
            GlobalConfiguration globalConfiguration) throws Exception {
        String mapperLocations = "classpath*:mapper/secondary/*.xml";
        String configLocation = "classpath:mybatis-sqlconfig.xml";
        String typeAliasesPackage = "com.firestone.bean.entity.mysql.secondary";
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
        // 数据源
        factory.setDataSource(dataSource);
        // 全局配置
        factory.setGlobalConfig(globalConfiguration);
        Interceptor[] interceptor = { new PaginationInterceptor() };
        // 分页插件
        factory.setPlugins(interceptor);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            // 自动扫描Mapping.xml文件
            factory.setMapperLocations(resolver.getResources(mapperLocations));
            factory.setConfigLocation(resolver.getResource(configLocation));
            factory.setTypeAliasesPackage(typeAliasesPackage);
            return factory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    // MyBatis 动态扫描
    @Bean(name = "secondaryMapperScannerConfigurer")
    public MapperScannerConfigurer mapperScannerConfigurer() {
        logger.info("初始化secondaryMapperScannerConfigurer");
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        String basePackage = "com.firestone.dao.secondary";
        mapperScannerConfigurer.setBasePackage(basePackage);
        return mapperScannerConfigurer;
    }

    @Bean(name = "secondaryTransactionManager")
    public DataSourceTransactionManager transactionManager(
            @Qualifier("secondaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "secondarySqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory)
                    throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
